<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import type {
  FormDesignerComponents,
  FormItemPerm
} from "../FormComponentMixin";
import { getDeptById } from "@/api/flow/auditor";
import { useUserStoreHook } from "@/store/modules/user";
import { isReadonly } from "../FormItem";
const props = defineProps({
  type: {
    type: String,
    default: ""
  },
  mode: {
    type: String,
    default: "normal" //组件模式，free设计模式，normal 编辑模式, read 阅读模式，disable 禁用模式
  }
});

const _value = defineModel<string>();
const _active = defineModel<FormDesignerComponents>("active");
const config = defineModel<FormDesignerComponents>("config");
const perm = inject<Array<FormItemPerm>>("perm");
const deptName = ref(null);
const emits = defineEmits(["change"]);

const disabled = computed(() => {
  if (props.mode === "disable" && isReadonly(perm, config.value.code)) {
    return true;
  }
  return false;
});

onMounted(() => {
  if (!_value.value) {
    const { deptid } = useUserStoreHook();
    _value.value = deptid;
    emits("change", config.value, deptid);
  }
});

watchEffect(() => {
  if (_value.value && !deptName.value) {
    getDeptById(_value.value as string).then(res => {
      if (res.code === 200) {
        deptName.value = res.data.text;
      }
    });
  }
});

const handleValueChange = val => {
  console.log("change", config.value, val);
  emits("change", config.value, val);
};
</script>

<template>
  <el-input
    v-model="deptName"
    :placeholder="deptName"
    :disabled="disabled"
    :readonly="true"
    :show-word-limit="true"
    :maxlength="config.props.maxlength"
    @change="handleValueChange"
  />
</template>

<style scoped></style>
